package com.lishe.lishe.lishe.module.mall.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.HttpUtils;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerGriadViewItemDecoration;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshHeaderLayout;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseFragment;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.module.mall.adapter.MallOtherGoodsBaseAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.category.Category;
import com.lishe.lishe.lishe.pulltorefresh.PullToRefreshBase;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.LinkedList;

import cz.msebera.android.httpclient.Header;


/**
 * Created by lwa on 2017/9/23
 * 商城-（除了全部外的其他）
 */
public class MallOtherGoodsFragment extends BaseFragment {

    private RefreshRecyclerView recyclerView;
    private Category category;
    private LinkedList<MallGoods> mallGoods = new LinkedList<>();//列表显示的商品
    private MallGoods mallGoodsHost = new MallGoods();//热点及横向显示的商品
    private MallOtherGoodsBaseAdapter mallOtherGoodsAdapter;
    private ImageLoaderUtils imageLoaderUtils;

    private RelativeLayout empty;
    private TextView emptyText;

    public static MallOtherGoodsFragment newInstance(Category category) {
        MallOtherGoodsFragment fragment = new MallOtherGoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("category", category);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        category = (Category) getArguments().getSerializable("category");
        mallOtherGoodsAdapter = new MallOtherGoodsBaseAdapter(getActivity(), mallGoods);
        imageLoaderUtils = new ImageLoaderUtils();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_mall_fregment_layout, container, false);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View view) {
        empty = view.findViewById(R.id.empty);
        emptyText = view.findViewById(R.id.text);

        recyclerView = view.findViewById(R.id.recycleView);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new RecyclerGriadViewItemDecoration(40, 2, 1));
        recyclerView.setOnItemClickListener(new RefreshRecyclerView.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                MallGoods mall = mallGoods.get(position);
                MallGoodsActivity.jump(getActivity(), mall.getItem_id());
            }
        });

        recyclerView.setOnRefreshListener(new RecyclerViewRefreshListener() {
            @Override
            public void onHeaderRefresh(View headerView) {
                String label = new Date().toLocaleString();
                // 更新显示的label
                ((RefreshHeaderLayout) headerView).setLable(label);
                getData();
            }

            @Override
            public void onFooterRefresh(View footerViwe) {

            }
        });
        recyclerView.setAdapter(mallOtherGoodsAdapter);
        recyclerView.setRefreshing();
        emptyText.setText("加载中...");
        if (mallGoods.size() == 0) {
            empty.setVisibility(View.VISIBLE);
        } else {
            empty.setVisibility(View.GONE);
        }
//        getData();
    }


    /**
     * 接口拿数据
     */
    private void getData() {
        if (category != null) {
            HttpUtils.get(category.getUrl() + "Goods/search/", null, goodsDataResposetUrl);
        }
    }


    AsyncHttpResponseHandler goodsDataResposetUrl = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            LoadingUtils.closeDialog();
            String result = new String(responseBody);
            recyclerView.setCompleteRefresh();
            Log.e("链接result", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray commodity = data.optJSONArray("commodity");
                    JSONObject floors = data.optJSONObject("floors");
                    JSONArray floorsItems = floors.optJSONArray("items");
                    mallGoods.clear();//商品列表
                    for (int i = 0; i < commodity.length(); i++) {//列表部分
                        MallGoods mallGood = new MallGoods();
                        JSONObject object = commodity.optJSONObject(i);
                        mallGood = JSON.parseObject(object.toString(), MallGoods.class);
                        mallGoods.add(mallGood);
                    }
                    //----------------------header 内容-------------------------------
                    mallGoodsHost.setImage_default_id(floors.optString("icon"));
                    mallGoodsHost.setTitle(floors.optString("name"));
                    mallGoodsHost.getItems().clear();//热点列表
                    for (int i = 0; i < floorsItems.length(); i++) {//前部分
                        MallGoods mallGood = new MallGoods();
                        JSONObject object = floorsItems.optJSONObject(i);
                        mallGood = JSON.parseObject(object.toString(), MallGoods.class);
                        mallGoodsHost.getItems().add(mallGood);
                    }
                    mallOtherGoodsAdapter.addHeaderView(initHeadView());
                    mallOtherGoodsAdapter.notifyDataSetChanged();
                    if (mallGoods.size() == 0) {
                        empty.setVisibility(View.VISIBLE);
                        emptyText.setText("没有商品，点击刷新！");
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                } else {
                    toast(result);
                    if (mallGoods.size() == 0) {
                        empty.setVisibility(View.VISIBLE);
                        emptyText.setText("没有商品，点击刷新！");
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                }
            } catch (JSONException e) {
                if (mallGoods.size() == 0) {
                    empty.setVisibility(View.VISIBLE);
                    emptyText.setText("没有商品，点击刷新！");
                } else {
                    empty.setVisibility(View.GONE);
                }
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
            LoadingUtils.closeDialog();
            recyclerView.setCompleteRefresh();
            if (mallGoods.size() == 0) {
                empty.setVisibility(View.VISIBLE);
                emptyText.setText("没有商品，点击刷新！");
            } else {
                empty.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 页面头部
     */
    private View initHeadView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_mall_other_header, null);
        ImageView img = view.findViewById(R.id.img);
        LinearLayout item_layout = view.findViewById(R.id.item_layout);
        item_layout.removeAllViews();
        imageLoaderUtils.displayImage(mallGoodsHost.getImage_default_id(), img);
        LinkedList<MallGoods> items = mallGoodsHost.getItems();
        for (final MallGoods mall : items) {
            View v = LayoutInflater.from(context).inflate(R.layout.item_mall_scroll, null);
            ImageView goods_img = v.findViewById(R.id.goods_img);
            TextView goods_name = v.findViewById(R.id.goods_name);
            TextView integral = v.findViewById(R.id.integral);
            imageLoaderUtils.displayImage(mall.getImage_default_id(), goods_img);
            goods_name.setText(mall.getTitle());
            integral.setText((int) ((float) mall.getPrice() * 100) + "");
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MallGoodsActivity.jump(getActivity(), mall.getItem_id());
                }
            });
            item_layout.addView(v);
        }
        return view;
    }
}
